package com.cdks.wuxiu.api.service.mysql;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdks.wuxiu.api.mapper.ChatMessageInfoMapper;
import com.cdks.wuxiu.api.model.dto.ChatMessageStatisDTO;
import com.cdks.wuxiu.api.util.TimeUtils;
import com.cdks.wuxiu.entity.mysql.ChatMessageInfo;

import java.util.List;

import org.springframework.stereotype.Service;


/**
 * 聊天消息 服务实现类
 */
@Service
public class ChatMessageInfoServiceImpl extends ServiceImpl<ChatMessageInfoMapper, ChatMessageInfo> implements ChatMessageInfoService {
    @Override
    public int saveMessage(long senderId, long recverId, int type, String data) {
        ChatMessageInfo msgInfo  = new ChatMessageInfo();
        msgInfo.setSenderId(senderId);
        msgInfo.setRecverId(recverId);
        msgInfo.setType(type);
        msgInfo.setCreateTime(TimeUtils.getTimeSecond());
        msgInfo.setContent(data);

        int ret  = baseMapper.insert(msgInfo);
        if (ret > 0)
        {
            return 0;
        }

        return -1;
    }

    @Override
    public int getMessageCount(long senderId, long recverId) {
        QueryWrapper<ChatMessageInfo> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(ChatMessageInfo::getSenderId, senderId)
                        .eq(ChatMessageInfo::getRecverId, recverId);

        return baseMapper.selectCount(wrapper);
    }

    @Override
    public int getMessageStatis(long senderId, long recverId) {
        int answerRate   = 0;

        List<ChatMessageStatisDTO> list  = baseMapper.getStatisList(senderId, recverId);
        for (ChatMessageStatisDTO data : list) {
            if (data.getRecvCnt() > data.getSendCnt())
            {
                answerRate += data.getSendCnt() * 100 / data.getRecvCnt();
            }
            else
            {
                answerRate += data.getRecvCnt() * 100 / data.getSendCnt();
            }
        }
        
        return answerRate / 3;
    }
}
